#!/bin/bash

#Parse from yaml
BOARD_PATH=$PATH_TG7101C_EVB
CHIP_PATH=$PATH_CHIP_TG7101C

PRODUCT_BIN=${BOARD_PATH}/configs/product.exe
WMTOOL=${BOARD_PATH}/configs/wm_tool.exe
ELF_NAME=`ls Obj/*.elf`

#Tools bin
OBJCOPY=csky-elfabiv2-objcopy

echo "[INFO] Generated output files ... ${CHIP_PATH}"

MK_GENERATED_IMGS_PATH=generated

#Dir prepare
rm -fr ${MK_GENERATED_IMGS_PATH}
mkdir -p ${MK_GENERATED_IMGS_PATH}
mkdir -p ${MK_GENERATED_IMGS_PATH}/data

# copy from chip
if [ -f "${CHIP_PATH}/wmsdk/tools/TG7101C/TG7101C_secboot.img" ]; then cp ${CHIP_PATH}/wmsdk/tools/TG7101C/TG7101C_secboot.img ${MK_GENERATED_IMGS_PATH}/; fi

# copy from board
if [ -f "${BOARD_PATH}/bootimgs/boot" ]; then cp ${BOARD_PATH}/bootimgs/boot ${MK_GENERATED_IMGS_PATH}/data/; fi
if [ -f "${BOARD_PATH}/configs/config.yaml" ]; then cp ${BOARD_PATH}/configs/config.yaml ${MK_GENERATED_IMGS_PATH}/data/; fi

${OBJCOPY} -O binary ${ELF_NAME} ${MK_GENERATED_IMGS_PATH}/data/prim

echo "[INFO] Create bin files"
${PRODUCT_BIN} image ${MK_GENERATED_IMGS_PATH}/images.zip -i ${MK_GENERATED_IMGS_PATH}/data -l -p
${PRODUCT_BIN} image ${MK_GENERATED_IMGS_PATH}/images.zip -e ${MK_GENERATED_IMGS_PATH}/data
${PRODUCT_BIN} image ${MK_GENERATED_IMGS_PATH}/images.zip -e ${MK_GENERATED_IMGS_PATH}/data -x

echo "[INFO] Create wm bin files： ${ProjectName}"
${OBJCOPY} -O binary Obj/smart_outlet_demo.elf ${MK_GENERATED_IMGS_PATH}/yoc.bin
${WMTOOL} -b ${MK_GENERATED_IMGS_PATH}/yoc.bin -fc 0 -it 1 -ih 80D0000 -ra 80D0400 -ua 8010000 -nh 0 -un 0
cat ${MK_GENERATED_IMGS_PATH}/TG7101C_secboot.img ${MK_GENERATED_IMGS_PATH}/yoc.img > ${MK_GENERATED_IMGS_PATH}/yoc.fls
${WMTOOL} -b ${MK_GENERATED_IMGS_PATH}/yoc.img -fc 1 -it 1 -ih 80D0000 -ra 80D0400 -ua 8010000 -nh 0 -un 0
mv ${MK_GENERATED_IMGS_PATH}/yoc_gz.img ${MK_GENERATED_IMGS_PATH}/yoc_ota.bin

echo "[INFO] Create fls file"
cp ${MK_GENERATED_IMGS_PATH}/data/boot ${MK_GENERATED_IMGS_PATH}/boot.bin
cp ${MK_GENERATED_IMGS_PATH}/data/prim ${MK_GENERATED_IMGS_PATH}/prim.bin
cp ${MK_GENERATED_IMGS_PATH}/data/imtb ${MK_GENERATED_IMGS_PATH}/imtb.bin
${WMTOOL} -b ${MK_GENERATED_IMGS_PATH}/boot.bin -fc 0 -it 512 -ih 8002000 -ra 8002400 -ua 8010000 -nh 80D0000 -un 0
${WMTOOL} -b ${MK_GENERATED_IMGS_PATH}/prim.bin -fc 0 -it 1 -ih 80D0000 -ra 80D0400 -ua 8010000 -nh 0 -un 0
${WMTOOL} -b ${MK_GENERATED_IMGS_PATH}/imtb.bin -fc 0 -it 1 -ih 20047400 -ra 81C0000 -ua 0 -nh 0 -un 0
cd ${MK_GENERATED_IMGS_PATH}
cat boot.img prim.img imtb.img > yoc_total.fls